package com.white.FalseWorld;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.gyf.immersionbar.ImmersionBar;
import com.white.FalseWorld.adapters.GrqAdapter;
import com.white.FalseWorld.beans.pyq;
import com.white.FalseWorld.others.DataCenter;
import com.white.FalseWorld.others.FriendsCircleAdapterDivideLine;
import com.white.FalseWorld.others.GlideSimpleTarget;
import com.white.FalseWorld.utils.DelectRecyviewBottom;
import com.white.FalseWorld.utils.Utils;
import com.white.FalseWorld.widgets.EmojiPanelView;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import ch.ielse.view.imagewatcher.ImageWatcher;
import io.reactivex.disposables.Disposable;

import static java.sql.DriverManager.getConnection;

public class GrqActivity extends AppCompatActivity implements  ImageWatcher.OnPictureLongPressListener, ImageWatcher.Loader{
    private Disposable mDisposable;
    private com.white.FalseWorld.adapters.GrqAdapter GrqAdapter;
    private com.white.FalseWorld.beans.pyq pyq_data;
    private ImageWatcher grq_mImageWatcher;
    private EmojiPanelView grq_mEmojiPanelView;
    RecyclerView grq_recyclerView;
    RelativeLayout grq_title_Bar;
    LinearLayout grq_year_layout;
    private TextView grq_wx_pyq_title,grq_wx_name,grq_wx_table,grq_year;
    private ImageView grq_wx_pyq_xj,grq_img_back,grq_wx_touxiang;

    private int imgWidth;
    private int imgHeight;
    private float mY;
    private float mX,m,d,x,y;
    private int ScreenX;
    private int ScreenY;
    private String user;
    private String temp_wx_pyq_picture,temp_user,temp_headpicture,temp_grq_wx_table;
    ArrayList<pyq> list = new ArrayList<pyq>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_grq );
        ImmersionBar.with(this).init();//一键透明状态栏

        /**
         * 获取登录页面传过来的账号[微信号]
         * 利用账号读取数据库相关信息（名字，头像地址，背景地址）
         */
        user = getIntent().getStringExtra("user");

        System.out.println( "传过来的微信号："+user );

        grq_mEmojiPanelView = findViewById(R.id.grq_emoji_panel_view);
        grq_mEmojiPanelView.initEmojiPanel( DataCenter.emojiDataSources);

        grq_recyclerView = findViewById(R.id.grq_recycler_view);

        grq_recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(GrqActivity.this).resumeRequests();
                } else {
                    Glide.with(GrqActivity.this).pauseRequests();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });


        grq_mImageWatcher = findViewById(R.id.grq_image_watcher);
        grq_recyclerView.setLayoutManager(new LinearLayoutManager(this));
        grq_recyclerView.addItemDecoration(new FriendsCircleAdapterDivideLine());

        grq_recyclerView.setLayoutManager(new LinearLayoutManager(this));

        //去除RecyclerView底部线条，影响美观
        DelectRecyviewBottom dividerItemDecoration = new DelectRecyviewBottom(this, DividerItemDecoration.HORIZONTAL);
        dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.recycler_divider));
        grq_recyclerView.addItemDecoration(dividerItemDecoration);

        grq_mImageWatcher.setTranslucentStatus( Utils.calcStatusBarHeight(this));
        grq_mImageWatcher.setErrorImageRes(R.mipmap.error_picture);
        grq_mImageWatcher.setOnPictureLongPressListener(this);
        grq_mImageWatcher.setLoader(this);


        //*******************************************
        grq_title_Bar=findViewById( R.id.grq_title_Bar );
        grq_wx_pyq_title=findViewById( R.id.grq_wx_pyq_title );
        grq_wx_pyq_xj=findViewById( R.id.grq_wx_pyq_xj );
        grq_img_back=findViewById( R.id.grq_img_back );
        grq_wx_name=findViewById( R.id.grq_wx_name );
        grq_wx_touxiang=findViewById( R.id.grq_wx_touxiang );
        grq_wx_table=findViewById( R.id.grq_wx_table );
        grq_year=findViewById( R.id.grq_year );
        grq_year_layout=findViewById( R.id.grq_year_layout );


        /* 取得屏幕对象 */
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        /* 取得屏幕解析像素 */
        ScreenX = dm.widthPixels;
        ScreenY = dm.heightPixels;

        pyq_query_mysql_init();

        grq_img_back.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        } );




    }

    //因为mysql在新线程中运行，所以得重新回到UI线程进行组件内容的修改等操作
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {

                Bundle data = msg.getData();
                ArrayList<pyq> temp_hand_list=new ArrayList<pyq>(  );

                String user = data.getString("user");
                String headpicture = data.getString("headpicture");
                String wx_pyq_picture = data.getString("wx_pyq_picture");
                String table=data.getString( "grq_wx_table" );
                ArrayList list = data.getParcelableArrayList("list");
                temp_hand_list= (ArrayList<pyq>) list.get(0);//强转成你自己定义的list，这样list2就是你传过来的那个list了。

                //配置recyclerView的适配器
                GrqAdapter = new GrqAdapter(GrqActivity.this, grq_recyclerView, temp_hand_list);
                grq_recyclerView.setAdapter(GrqAdapter);

                //设置UI
                Glide.with(getApplicationContext())
                        .asBitmap()
                        .load(wx_pyq_picture)
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                Drawable drawable = new BitmapDrawable(resource);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                    grq_title_Bar.setBackground(drawable);
                                }
                            }

                        });
                Glide.with(getApplicationContext())
                        .asBitmap()
                        .load(headpicture)
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                Drawable drawable = new BitmapDrawable(resource);
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                    grq_wx_touxiang.setImageDrawable(drawable);
                                }
                            }

                        });

                grq_wx_name.setText( user );
                grq_wx_table.setText( table );
                if (String.valueOf( temp_hand_list.get( 0 ).getPyq_year() ).length()==0){
                    grq_year.setText( "未发布");
                }else {
                    grq_year.setText( String.valueOf( temp_hand_list.get( 0 ).getPyq_year() ) +"年");
                }

                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) grq_wx_name
                        .getLayoutParams();
                params.rightMargin=10;
                grq_wx_name.setLayoutParams( params );
                System.out.println( "名字："+temp_user+"头像地址："+temp_headpicture+"  背景地址"+ temp_wx_pyq_picture);
                // Toast.makeText(getApplicationContext(),"请求资源成功",Toast.LENGTH_LONG).show();
            } else if (msg.what ==0) {
                Toast.makeText(getApplicationContext(),"请求资源不成功",Toast.LENGTH_LONG).show();
            }
        }
    };

    //对数据库进行查询工作，拿取相对应的信息
    private void pyq_query_mysql_init() {
        new Thread( new Runnable() {
            @Override
            public void run() {
                try {
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection cn= getConnection( getString( R.string.mysql_address ),getString( R.string.mysql_username ),getString( R.string.mysql_password ));
                    System.out.println("连接数据库成功");
                    String sql="SELECT * FROM personals WHERE user_wx= '"+user+"'";
                    String sql1="SELECT * FROM pyq WHERE user_id=(SELECT user_id FROM personals WHERE user_wx='"+user+"') ORDER BY pyq_id DESC";
                    Statement st=(Statement)cn.createStatement();

                    ResultSet rs=st.executeQuery(sql);
                    while(rs.next()){
                        temp_user=rs.getString("user");
                        temp_headpicture=rs.getString( "headpicture" );
                        temp_wx_pyq_picture=rs.getString( "wx_pyq_picture" );
                        temp_grq_wx_table=rs.getString( "wx_pyq_label" );
                        System.out.println( "11111名字："+temp_user+"头像地址："+temp_headpicture+"  背景地址"+ temp_wx_pyq_picture);
                    }

                    rs=st.executeQuery(sql1);
                    while(rs.next()){
                        int pyq_id=rs.getInt( "pyq_id" );
                        int pyq_type=rs.getInt( "pyq_type" );
                        int pyq_day=rs.getInt( "pyq_day" );
                        int pyq_mouth=rs.getInt( "pyq_mouth" );
                        int pyq_year=rs.getInt( "pyq_year" );
                        /**
                         *
                         * pyq_type朋友圈类型分类：
                         * 1：纯文本
                         * 2：图片+文本
                         * 3：网页（图片+文本）
                         * 4：文本+网页（图片+文本）
                         * @return
                         */
                        pyq_data=new pyq();
                        pyq_data.setPyq_type( pyq_type );
                        pyq_data.setPyq_id( pyq_id );
                        pyq_data.setPyq_day(pyq_day);
                        pyq_data.setPyq_mouth(pyq_mouth);
                        pyq_data.setPyq_year(pyq_year);
                        if (pyq_type==1){
                            String pyq_text=rs.getString( "pyq_text" );
                            pyq_data.setPyq_text( pyq_text );
                        }else if(pyq_type==2){
                            String pyq_text=rs.getString( "pyq_text" );
                            String pyq_picture=rs.getString( "pyq_picture_href" );
                            if (pyq_picture.contains( "," )){
                                pyq_picture=getString( R.string.url_prefix )+pyq_picture.split( "," )[0];
                            }
                            pyq_data.setPyq_text( pyq_text );
                            pyq_data.setPyq_picture_href( pyq_picture );
                        }else if(pyq_type==3){
                            String pyq_web_text=rs.getString( "pyq_web_text" );
                            String pyq_web_picture=getString( R.string.url_prefix )+rs.getString( "pyq_web_picture" );
                            pyq_data.setPyq_web_text( pyq_web_text );
                            pyq_data.setPyq_web_picture( pyq_web_picture );
                        }else if(pyq_type==4){
                            String pyq_text=rs.getString( "pyq_text" );
                            String pyq_web_text=rs.getString( "pyq_web_text" );
                            String pyq_web_picture=getString( R.string.url_prefix )+rs.getString( "pyq_web_picture" );
                            pyq_data.setPyq_text( pyq_text );
                            pyq_data.setPyq_web_text( pyq_web_text );
                            pyq_data.setPyq_web_picture( pyq_web_picture );
                        }
                        list.add( pyq_data );
                        System.out.println( "朋友圈id："+pyq_data.getPyq_id()+"类型："+pyq_data.getPyq_type()+"日："+pyq_data.getPyq_day());
                    }

                    System.out.println( "2222名字："+temp_user+"头像地址："+temp_headpicture+"  背景地址"+ temp_wx_pyq_picture);
                    //System.out.println( "朋友圈id："+pyq_data.getPyq_id()+"类型："+pyq_data.getPyq_type()+"日："+pyq_data.getPyq_day());
                    cn.close();
                    st.close();
                    rs.close();
                    Message msg = new Message();
                    Bundle data = new Bundle();

                    ArrayList temp_list=new ArrayList(  );
                    temp_list.add( list );
                    //将获取到的String装载到msg中
                    data.putString("user", temp_user);
                    data.putString("headpicture", getString( R.string.url_prefix )+temp_headpicture);
                    data.putString("wx_pyq_picture", getString( R.string.url_prefix )+temp_wx_pyq_picture);
                    data.putString( "grq_wx_table",temp_grq_wx_table );
                    data.putParcelableArrayList( "list",temp_list );

                    msg.setData(data);
                    msg.what = 1;
                    //发消息到主线程
                    handler.sendMessage(msg);
                    System.out.println("连接数据库操作执行完毕");
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } ).start();
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        imgWidth = (int) event.getX();
        imgHeight =300;

        // TODO Auto-generated method stub
        /*获取手触屏的位置*/
        m=event.getX();
        d=event.getY();
        x = event.getX()-45;
        y = event.getY()-160;

        /*默认微调图片与指针的相对位置*/
        mX=x-(imgWidth/2);
        mY=y-(imgHeight/2);

        /*分开处理触摸的时间*/
        switch (event.getAction()) {

            /*点屏幕*/
            case MotionEvent.ACTION_DOWN  :

//                title_Bar.setLayoutParams(new
//                        AbsoluteLayout.LayoutParams
//                        (imgWidth, imgHeight, (int)mX,(int)mY));

                break;
            /*移动位置*/
            case MotionEvent.ACTION_MOVE  :

//                title_Bar.setLayoutParams(new
//                        AbsoluteLayout.LayoutParams
//                        (imgWidth, imgHeight, (int)mX,(int)mY));
                moveViewWithFinger(grq_title_Bar,event.getX(),event.getRawX(),event.getRawY());

                break;

            /*离开屏幕*/
            case MotionEvent.ACTION_UP  :

//                title_Bar.setLayoutParams(new
//                        AbsoluteLayout.LayoutParams
//                        (imgWidth, imgHeight, (int)mX,(int)mY));

                break;

            default:
                break;
        }

        return true;
    }
    private void moveViewWithFinger(RelativeLayout view, float getx,float rawX, float rawY) {
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view
                .getLayoutParams();

        int c=(int) rawY - 300 / 2;

        System.out.println( "  背景地址"+ temp_wx_pyq_picture);

        /*
         * 判断，当头部布局到达180停止往上滑，并且显示["朋友圈"]文字，背景颜色为灰色
         * 当头部布局达到700停止往下滑,view的背景照片恢复正常  (未完成)
         * */
        if (c<=180){
            grq_year_layout.setVisibility( View.VISIBLE );
            grq_wx_pyq_title.setVisibility( View.VISIBLE );
            grq_year_layout.setBackgroundColor( Color.parseColor( "#f0f0f0" ) );
            view.setBackgroundColor( Color.parseColor( "#efefef" ));
            grq_img_back.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(),R.drawable.fx_b ));
            grq_wx_pyq_xj.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(),R.drawable.pl_b ));

        }else if (c>=900){
            grq_year_layout.setVisibility( View.INVISIBLE );
            grq_wx_pyq_title.setVisibility( View.INVISIBLE );
            grq_year_layout.setBackgroundColor( Color.parseColor( "#ffffff" ) );
            grq_img_back.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(),R.drawable.fx_w ));
            grq_wx_pyq_xj.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(),R.drawable.pl_w ));
            Glide.with(GrqActivity.this)
                    .asBitmap()
                    .load(getString( R.string.url_prefix )+temp_wx_pyq_picture)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                            Drawable drawable = new BitmapDrawable(resource);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                grq_title_Bar.setBackground(drawable);
                            }
                        }

                    });
        }else{

            params.height = (int) rawY - 300 / 2;
            grq_year_layout.setVisibility( View.INVISIBLE );
            grq_wx_pyq_title.setVisibility( View.INVISIBLE );
            grq_year_layout.setBackgroundColor( Color.parseColor( "#ffffff" ) );
            grq_img_back.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(),R.drawable.fx_w ));
            grq_wx_pyq_xj.setImageDrawable( ContextCompat.getDrawable(getApplicationContext(),R.drawable.pl_w ));
            view.setLayoutParams(params);
            Glide.with(GrqActivity.this)
                    .asBitmap()
                    .load(getString( R.string.url_prefix )+temp_wx_pyq_picture)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                            Drawable drawable = new BitmapDrawable(resource);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                grq_title_Bar.setBackground(drawable);
                            }
                        }

                    });
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }



    @Override
    public void onBackPressed() {
        if (!grq_mImageWatcher.handleBackPressed()) {
            super.onBackPressed();
        }
    }

    @Override
    public void onPictureLongPress(ImageView v, String url, int pos) {

    }


    @Override
    public void load(Context context, String url, ImageWatcher.LoadCallback lc) {
        Glide.with(context).asBitmap().load(url).into(new GlideSimpleTarget(lc));
    }
}
